package com.leyou.user.controller;


import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 数据校验
     *
     * @param data
     * @param type
     * @return
     */
    @GetMapping("check/{data}/{type}")
    public ResponseEntity<Boolean> checkUserData(
            @PathVariable("data") String data,
            @PathVariable("type") Integer type
    ) {

        Boolean boo = this.userService.checkUserData(data, type);

        if (boo == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        return ResponseEntity.ok(boo);
    }

    /**
     * 生成短信验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone") String phone) {

        Boolean boo = this.userService.sendVerifyCode(phone);

        if (boo == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 用户的注册
     *
     * @param code
     * @return
     */
    @PostMapping("register")
    public ResponseEntity<Void> register(
            @Valid User user,
            @RequestParam("code") String code

    ) {

        //获取验证结果
        Boolean boo = this.userService.register(user, code);

        if (boo == null || !boo) {
            //返回失败400
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        //返回成功201
        return new ResponseEntity<>(HttpStatus.CREATED);

    }


    @GetMapping("query")
    public ResponseEntity<User> queryUser(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ) {
        User user = this.userService.queryUser(username, password);

        if (user == null){
            //返回失败400
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return ResponseEntity.ok(user);
    }
}
